<template>
  <div>
    <Modal
      :mask-closable="false"
      v-model="showConsumption"
      @on-visible-change="
        (e) => {
          !e && $emit('closeConsumption', false);
        }
      "
      :width="1200"
      title="投流消费"
      :footer-hide="true"
      :draggable="true"
    >
      <Form>
        <Row>
          <Col span="20">
            <FormItem label="">
              <DatePicker
                v-model="params.date"
                type="daterange"
                :options="options"
                placeholder="日期选择"
                @on-change="searchData"
              />
            </FormItem>
          </Col>
          <Col span="4" class="ivu-text-right">
            <Button
              type="primary"
              @click="handleAdd"
              v-hasC="{
                name: 'v1-buss-accounts-create-consume',
                flag: 'v1/buss/accounts/create-consume',
              }"
              >新增投放</Button
            >
          </Col>
        </Row>
      </Form>
      <Table
        :max-height="400"
        :columns="columns"
        @on-sort-change="sortChange"
        :data="list"
        :loading="loading"
      >
        <template #effective_clue_num="{ row }">
          <span v-if="currentId != row.id">{{ row.effective_clue_num }}</span>
          <inputNumber
            v-else
            v-model="dataInfo.effective_clue_num"
            type="number"
          />
        </template>
        <template #private_sms_num="{ row }">
          <span v-if="currentId != row.id">{{ row.private_sms_num }}</span>
          <inputNumber
            v-else
            v-model="dataInfo.private_sms_num"
            type="number"
          />
        </template>
        <template #give_mobile_num="{ row }">
          <span v-if="currentId != row.id">{{ row.give_mobile_num }}</span>
          <inputNumber
            v-else
            v-model="dataInfo.give_mobile_num"
            type="number"
          />
        </template>
        <template #recommend_num="{ row }">
          <span v-if="currentId != row.id">{{ row.recommend_num }}</span>
          <inputNumber v-else v-model="dataInfo.recommend_num" type="number" />
        </template>
        <template #hour_minute="{ row }">
          {{ row.hour_minute.substr(0, 5) }}
        </template>
        <template #action="{ row }">
          <span v-if="currentId != row.id">
            <a
              @click="handleData(row)"
              v-hasC="{
                name: 'v1-buss-accounts-update-consume-data',
                flag: 'v1/buss/accounts/update-consume-data',
              }"
              >数据</a
            >
            <Divider
              type="vertical"
              v-hasC="{
                name: 'v1-buss-accounts-update-consume-data',
                flag: 'v1/buss/accounts/update-consume-data',
              }"
            />
            <a
              @click="handleEdit(row)"
              v-hasC="{
                name: 'v1-buss-accounts-update-consume',
                flag: 'v1/buss/accounts/update-consume',
              }"
              >编辑</a
            >
            <Divider
              type="vertical"
              v-hasC="{
                name: 'v1-buss-accounts-update-consume',
                flag: 'v1/buss/accounts/update-consume',
              }"
            />
            <a
              @click="handleDel(row.id)"
              class="del"
              v-hasC="{
                name: 'v1-buss-accounts-delete-consume',
                flag: 'v1/buss/accounts/delete-consume',
              }"
              >删除</a
            >
          </span>
          <span v-if="currentId == row.id">
            <Button
              size="small"
              type="success"
              @click="saveData"
              :loading="btnLoading"
              >保存</Button
            >
            <Button
              size="small"
              class="ivu-ml-8"
              type="default"
              @click="currentId = -1"
              >取消</Button
            >
          </span>
        </template>
      </Table>
      <Page
        class="ivu-mt-16"
        :total="total"
        :modelValue="params.current"
        :page-size="params.size"
        :page-size-opts="pageOpts"
        show-total
        show-sizer
        @on-change="changePage"
        @on-page-size-change="changepageSize"
      />
    </Modal>

    <Modal
      :mask-closable="false"
      v-model="showModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="formInfo" :rules="rules" :label-width="90">
        <FormItem label="日期" prop="date_time" required>
          <DatePicker
            v-model="formInfo.date_time"
            type="date"
            :options="options"
            placeholder="请选择日期"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="金额" prop="money" required>
          <inputNumber
            v-model="formInfo.money"
            type="number"
            :active-change="false"
            :precision="2"
            placeholder="请输入金额"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="投放地区" prop="city_id" required>
          <Select
            placeholder="请选择投放地区"
            v-model="formInfo.city_id"
            multiple
            :filterable="cityList.length >= 10"
            clearable
          >
            <Option
              v-for="item in cityList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="时长" prop="hours" required>
          <inputNumber
            v-model="formInfo.hours"
            type="number"
            :max="23"
            :min="1"
            :active-change="false"
            :precision="0"
            placeholder="请输入时长"
            style="width: 100%"
          />
        </FormItem>
        <FormItem label="投放类型" prop="type">
          <Select placeholder="投放类型" v-model="formInfo.type" clearable>
            <Option
              v-for="item in typeList"
              :value="item.value + ''"
              :key="item.value"
              >{{ item.label }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="投放时间" prop="hour_minute" required>
          <TimePicker
            format="HH:mm"
            v-model="formInfo.hour_minute"
            placeholder="投放时间"
            style="width: 100%"
          />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="showModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import dayjs from "dayjs";
import {
  consumeList,
  consumeCreate,
  consumeUpdate,
  consumeDel,
  consumeDataUpdate,
} from "@api/accountnumber.js";
export default {
  name: "consumption",
  props: ["showConsumption", "id"],
  data() {
    return {
      loading: false,
      btnLoading: false,
      showModal: false,
      edit: true,
      currentId: -1,
      columns: [
        {
          key: "date_time_str",
          title: "日期",
          width: 110,
        },
        {
          key: "money",
          title: "金额",
          width: 100,
          sortable: "custom",
        },
        {
          key: "city_name",
          title: "投放地区",
          minWidth: 180,
        },
        {
          key: "hours",
          title: "时长",
          width: 80,
          sortable: "custom",
        },
        {
          key: "type_str",
          title: "投放类型",
          width: 110,
        },
        {
          slot: "hour_minute",
          title: "投放时间",
          width: 100,
        },
        {
          slot: "effective_clue_num",
          title: "有效评论",
          width: 110,
          sortable: "custom",
        },
        {
          slot: "private_sms_num",
          title: "有效私信",
          width: 110,
          sortable: "custom",
        },
        {
          slot: "give_mobile_num",
          title: "留电",
          width: 110,
          sortable: "custom",
        },
        {
          slot: "recommend_num",
          title: "推荐",
          width: 110,
          sortable: "custom",
        },
        {
          slot: "action",
          title: "操作",
          width: 160,
          fixed: "right",
        },
      ],
      list: [],
      total: 0,
      typeList: [],
      cityList: [],
      pageOpts: [10, 20, 30, 40],
      params: {
        id: this.id,
        date: [],
        current: 1,
        size: 10,
        order_column: "",
        order_sort: "",
      },
      formInfo: {
        id: "",
        account_id: this.id,
        money: null,
        date_time: this.$Date().format("YYYY-MM-DD"),
        city_id: "",
        hours: null,
        type: null,
        hour_minute: this.$Date().format("HH:mm"),
      },
      dataInfo: {
        consume_id: "",
        private_sms_num: "",
        effective_clue_num: "",
        give_mobile_num: "",
        recommend_num: "",
      },
      rules: {
        date_time: [{ required: true, message: "请选择日期" }],
        money: [{ required: true, message: "请输入金额" }],
        city_id: [{ required: true, message: "请选择城市" }],
        hours: [{ required: true, message: "请输入时长" }],
        type: [{ required: true, message: "请选择投放类型" }],
        hour_minute: [{ required: true, message: "请选择投放时间" }],
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
    };
  },
  watch: {
    showConsumption() {
      if (this.showConsumption) {
        this.params.date = [];
        this.params.current = 1;
        this.params.size = 10;
        this.params.id = this.id;
        this.formInfo.account_id = this.id;
        this.getData();
      }
    },
  },
  methods: {
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    sortChange(e) {
      this.params.order_column = e.key
        ? e.key.replace(/_str$/, "")
        : e.column.slot.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    searchData() {
      this.params.current = 1;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          consumeDel({ consume_id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      this.showModal = true;
      this.currentId = -1;
      this.edit = true;
      this.$refs.create.resetFields();
      this.formInfo = {
        id: "",
        account_id: this.id,
        money: null,
        date_time: this.$Date().format("YYYY-MM-DD"),
        city_id: "",
        hours: null,
        type: null,
        hour_minute: this.$Date().format("HH:mm"),
      };
    },
    handleEdit(row) {
      this.showModal = true;
      this.currentId = -1;
      this.edit = false;
      this.$refs.create.resetFields();
      this.formInfo = {
        id: row.id,
        account_id: row.account_id,
        money: +row.money,
        date_time: row.date_time_str,
        city_id: row.city_id.split(","),
        hours: +row.hours,
        type: row.type,
        hour_minute: row.hour_minute,
      };
    },
    editConsumption() {
      this.btnLoading = true;
      if (this.edit) {
        let params = {
          account_id: this.formInfo.account_id,
          money: this.formInfo.money,
          date_time: this.formInfo.date_time,
          city_id: this.formInfo.city_id.join(","),
          hours: this.formInfo.hours,
          type: this.formInfo.type,
          hour_minute: this.formInfo.hour_minute,
        };
        consumeCreate(params)
          .then(() => {
            this.$Message.success("新增成功");
            this.showModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        let params = {
          id: this.formInfo.id,
          account_id: this.formInfo.account_id,
          money: this.formInfo.money,
          date_time: this.formInfo.date_time,
          city_id: this.formInfo.city_id.join(","),
          hours: this.formInfo.hours,
          type: this.formInfo.type,
          hour_minute: this.formInfo.hour_minute,
        };
        consumeUpdate(params)
          .then(() => {
            this.$Message.success("编辑成功");
            this.showModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.editConsumption();
        } else {
          this.showModal = true;
          return;
        }
      });
    },
    handleData(row) {
      this.currentId = row.id;
      this.dataInfo = {
        consume_id: row.id,
        private_sms_num: row.private_sms_num ? +row.private_sms_num : null,
        effective_clue_num: row.effective_clue_num
          ? +row.effective_clue_num
          : null,
        give_mobile_num: row.give_mobile_num ? +row.give_mobile_num : null,
        recommend_num: row.recommend_num ? +row.recommend_num : null,
      };
    },
    saveData() {
      let params = {
        consume_id: this.dataInfo.consume_id,
        private_sms_num: this.dataInfo.private_sms_num,
        effective_clue_num: this.dataInfo.effective_clue_num,
        give_mobile_num: this.dataInfo.give_mobile_num,
        recommend_num: this.dataInfo.recommend_num,
      };
      this.btnLoading = true;
      consumeDataUpdate(params)
        .then(() => {
          this.btnLoading = false;
          this.currentId = -1;
          this.$Message.success("编辑成功");
          this.getData();
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    getData() {
      this.loading = true;
      let params = {
        id: this.params.id,
        date_stime: this.params.date[0]
          ? dayjs(this.params.date[0]).format("YYYY-MM-DD")
          : "",
        date_etime: this.params.date[1]
          ? dayjs(this.params.date[1]).format("YYYY-MM-DD")
          : "",
        page: this.params.current,
        pageSize: this.params.size,
        order_sort: this.params.order_sort,
        order_column: this.params.order_column,
      };
      consumeList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.cityList = res.condition.city;
          this.typeList = res.condition.type;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
